package com.markerhub.application.service;

import com.alibaba.fastjson.JSON;
import com.markerhub.vo.SmsParam;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class SmsService {
    @Value("${sms.https}")
    private String https;

    @Value("${sms.Content-Type}")
    private String contentType;

    @Value("${sms.apikey}")
    private String apikey;

    @Value("${sms.secret}")
    private String secret;

    @Value("${sms.sign_id}")
    private String signId;

    @Value("${sms.template_id}")
    private String templateId;

    public String sendSms(SmsParam smsParam){
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(https);
        httpPost.addHeader("Content-Type",contentType);
        Map<String,Object> map = new HashMap<>();
        map.put("apikey",apikey);
        map.put("secret",secret);
        map.put("sign_id",signId);
        map.put("template_id",templateId);
        map.put("mobile",smsParam.getMobile());
        map.put("content",smsParam.getContent());
        String json = JSON.toJSONString(map);
        httpPost.setEntity(new StringEntity(json,"UTF-8"));

        HttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String res = EntityUtils.toString(entity);
            return res;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
